package com.lyp.adapters;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.TextView;

import com.lyp.activitys.IndependentActivity;
import com.lyp.jsonbean.RenYuanBean;
import com.tjl.yangxixis.R;

import java.util.HashMap;
import java.util.List;

/**
 * 作者:ChenXi 时间:2017/6/9 14: 25
 */
//人员

public class IndepenAdapter extends RecyclerView.Adapter<IndepenAdapter.MyViewHolder>{

    private List<RenYuanBean.DataBean> mList;
    HashMap<String,Boolean> states=new HashMap<String,Boolean>();//用于记录每个RadioButton的状态，并保证只可选一个

    private Context mContext;
    public IndepenAdapter(List<RenYuanBean.DataBean> list,Context context) {
        mList = list;
        mContext = context;
    }

    @Override
    public IndepenAdapter.MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        IndepenAdapter.MyViewHolder holder = new IndepenAdapter.MyViewHolder(LayoutInflater.from
                (viewGroup.getContext()).inflate(R.layout.item_indepen, viewGroup, false));
        return holder;
    }

    @Override
    public void onBindViewHolder(final IndepenAdapter.MyViewHolder myViewHolder, final int i) {
        myViewHolder.mName.setText(mList.get(i).getUser());
        if (mList.get(i).getManager().equals("0")){
            myViewHolder.mManager.setText("施工人员");
        }
        else if (mList.get(i).getManager().equals("1")){
            myViewHolder.mManager.setText("销售经理");
        }

        //当RadioButton被选中时，将其状态记录进States中，并更新其他RadioButton的状态使它们不被选中
        myViewHolder.radio.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                IndependentActivity.index = i;
                //重置，确保最多只有一项被选中
                for(String key:states.keySet()){
                    states.put(key, false);
                }
                states.put(String.valueOf(i), myViewHolder.radio.isChecked());
                IndepenAdapter.this.notifyDataSetChanged();
            }
        });

        boolean res=false;
        if(states.get(String.valueOf(i)) == null || states.get(String.valueOf(i))== false){
            res=false;
            states.put(String.valueOf(i), false);
        }
        else
            res = true;

        myViewHolder.radio.setChecked(res);
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {

        TextView mName;
        TextView mManager;
        RadioButton radio;

        public MyViewHolder(View view)
        {
            super(view);
            mName = (TextView) view.findViewById(R.id.indepen_name);
            mManager = (TextView) view.findViewById(R.id.indepen_manager);
            radio=(RadioButton) view.findViewById(R.id.radio_btn);
        }
    }
}
